package com.example.demo.leetcode.top100;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _28两数相加
 * @description
 * @date 2023/06/11 10:35
 * <p>
 * ******************************************************
 */
public class _28两数相加 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        addTwoNumber(dummy, l1, l2, 0);
        return dummy.next;
    }

    private void addTwoNumber(ListNode dummy, ListNode l1, ListNode l2, int next) {

        if (l1 != null && l2 != null) {
            int i = l1.val + l2.val + next;
            dummy.next = new ListNode(i % 10);
            addTwoNumber(dummy.next, l1.next, l2.next, i/10);
        } else if (l1 != null) {
            int i = l1.val + next;
            dummy.next = new ListNode(i % 10);
            addTwoNumber(dummy.next, l1.next, null, i/10);
        } else if (l2 != null) {
            int i = l2.val + next;
            dummy.next = new ListNode(i % 10);
            addTwoNumber(dummy.next, null, l2.next, i/10);
        } else {
            if (next != 0) {
                dummy.next = new ListNode(next % 10);
            }
        }
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
